﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace InstallManager.Msi
{
    internal class MsiCommand : IDisposable
    {
        private string _command;

        private MsiConnection _conn;

        private bool _disposed;

        private IntPtr _view;

        internal IntPtr Handle
        {
            get
            {
                this.CheckDisposed();
                return this._view;
            }
        }

        public MsiCommand(string command, MsiConnection conn)
        {
            this._command = command;
            this._conn = conn;
        }

        private void CheckDisposed()
        {
            if (this._disposed)
            {
                throw new ObjectDisposedException("MSI");
            }
        }

        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool disposing)
        {
            if (!this._disposed && this._view != IntPtr.Zero)
            {
                MsiDbInterop.MsiCloseHandle(this._view);
                this._view = IntPtr.Zero;
                this._disposed = true;
            }
        }

        public MsiDataReader ExecuteReader()
        {
            this.CheckDisposed();
            if (this._conn.Handle == IntPtr.Zero)
            {
                throw new Exception("Database connection not opened.");
            }
            uint num = MsiDbInterop.MsiDatabaseOpenView(this._conn.Handle, this._command, out this._view);
            if (num != 0)
            {
                throw new Exception(string.Concat("Failed to create command. Error code = ", num));
            }
            return new MsiDataReader(this);
        }

       
    }
}
